package com.intelligentmeterreadingsys.report.activity;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;

import com.intelligentmeterreadingsys.R;
import com.intelligentmeterreadingsys.otherequipment.activity.EquipementAddActivity;
import com.intelligentmeterreadingsys.report.db.ReportDao;
import com.intelligentmeterreadingsys.util.BitmapUtil;

/**
 * 工程单添加图片
 * 
 * @author king
 * 
 */
public class OrderImageActivity extends Activity implements OnItemSelectedListener, ViewFactory {
    public static final int ITEM0 = Menu.FIRST;// 系统值
    private static final int REQUEST_CODE_TAKE_IMAGE = 1;
    private ImageSwitcher imgsw;

    private Gallery gallery;

    private Context mContext;

    private String otherid = null;
    private String status = null;

    public boolean b = false;

    public int poston;// 当前位置
    public ArrayList<String> imagepath = new ArrayList<String>();
    public String classname;
    public String imgpath = null;

    private Bitmap bitmap = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

	super.onCreate(savedInstanceState);

	requestWindowFeature(Window.FEATURE_NO_TITLE);
	setContentView(R.layout.image_switcher_activity);

	imgsw = (ImageSwitcher) findViewById(R.id.imgswch1);
	gallery = (Gallery) findViewById(R.id.gallery);
	init();
	Intent intent = getIntent();
	Bundle bundle = intent.getExtras();

	otherid = bundle.getString("otherid");
	classname = bundle.getString("classname");

	status = bundle.getString("status");
	if (otherid != null && !otherid.equals("")) {
	    ReportDao dao = new ReportDao(this);
	    imagepath = dao.queryImagePath(otherid);
	    dao.close();
	    if (imagepath == null || imagepath.size() < 1) {

		// Photograph();
		Intent intents = new Intent(OrderImageActivity.this, ScrawlActivity.class);
		intents.putExtra("classname", "OrderImageActivity");
		intents.putExtra("imgpath", "");
		startActivityForResult(intents, REQUEST_CODE_TAKE_IMAGE);

	    }

	}

    }

    @Override
    /**
     * ʵ�ֵ�ViewFactory�ӿ�
     */
    public View makeView() {
	ImageView i = new ImageView(this);
	i.setBackgroundColor(0xFF000000);
	i.setScaleType(ImageView.ScaleType.FIT_CENTER);
	i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
	return i;

    }

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

	if (!b) {
	    imgsw.setImageResource(R.drawable.contraband);
	} else {
	    Uri uri = Uri.parse(imagepath.get(arg2));
	    imgsw.setImageURI(uri);
	}

	poston = arg2;

    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {

    }

    public class ImageAdapter extends BaseAdapter {
	public ImageAdapter(Context c) {
	    mContext = c;
	}

	@Override
	public int getCount() {

	    if (!b) {

		return 1;
	    }
	    return imagepath.size();

	}

	@Override
	public Object getItem(int position) {

	    return position;
	}

	@Override
	public long getItemId(int position) {

	    return position;
	}

	@Override
	/**
	 * ���ImageView
	 */
	public View getView(int position, View convertView, ViewGroup parent) {

	    ImageView i = new ImageView(mContext);
	    if (!b) {
		i.setImageResource(R.drawable.contraband);
	    } else {
		FileInputStream f;
		try {
		    f = new FileInputStream(imagepath.get(position));
		    FileDescriptor fd = f.getFD();

		    BitmapFactory.Options options = new BitmapFactory.Options();
		    options.inJustDecodeBounds = true;
		    BitmapFactory.decodeFileDescriptor(fd, null, options);

		    options.inSampleSize = BitmapUtil.computeSampleSize(options, 80, 128 * 128);

		    options.inJustDecodeBounds = false;
		    Bitmap bm = BitmapFactory.decodeStream(f, null, options);

		    i.setImageBitmap(bm);
		} catch (FileNotFoundException e) {

		    e.printStackTrace();
		} catch (IOException e) {

		    e.printStackTrace();
		}

	    }

	    i.setAdjustViewBounds(true);
	    i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));// ͼƬ��С
	    if (b)
		i.setBackgroundResource(R.drawable.contraband);// ͼƬ����
	    return i;
	}

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
	menu.add(0, ITEM0, 0, "拍照");
	menu.add(0, ITEM0 + 1, 0, "删除");
	menu.add(0, ITEM0 + 2, 0, "编辑");
	menu.findItem(ITEM0 + 1);

	return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
	if (item.getItemId() == ITEM0) {
	    Photograph();
	} else if (item.getItemId() == ITEM0 + 1) {

	    delect();
	} else if (item.getItemId() == ITEM0 + 2) {
	    Intent intents = new Intent(OrderImageActivity.this, ScrawlActivity.class);
	    intents.putExtra("classname", "OrderImageActivity");
	    intents.putExtra("imgpath", imagepath.get(poston));
	    startActivityForResult(intents, REQUEST_CODE_TAKE_IMAGE);
	}

	return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	if (requestCode == REQUEST_CODE_TAKE_IMAGE) {

	    if (resultCode == RESULT_OK) {

		try {

		    imgpath = data.getStringExtra("imgpath");
		    boolean bb = data.getBooleanExtra("ismodify", false);

		    if (!bb) {
			FileInputStream fis = new FileInputStream(imgpath);

			bitmap = BitmapFactory.decodeStream(fis);

			imagepath.add(imgpath);
			b = true;
			init();
		    } else {
			b = false;
			init();
		    }

		} catch (FileNotFoundException e) {
		    e.printStackTrace();
		}

	    } else if (resultCode == RESULT_CANCELED) {

		b = false;
		init();
	    }
	}
	super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onRestart() {
	System.out.println("onRestart");

	super.onRestart();
    }

    /**
     * 初始化
     */
    public void init() {
	imgsw.removeAllViews();
	imgsw.setFactory(this);
	imgsw.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
	imgsw.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));
	gallery.setAdapter(new ImageAdapter(this));
	gallery.setOnItemSelectedListener(this);

    }

    /**
     * 删除一张照片
     */
    public void delect() {
	if (!b) {
	    Toast.makeText(this, "没有图片不能进行此抄作", Toast.LENGTH_LONG).show();
	    return;
	}

	File file = new File(imagepath.get(poston));
	file.delete();
	imagepath.remove(poston);
	if (imagepath.size() < 1) {
	    b = false;
	}
	init();

	Toast.makeText(this, "删除成功", Toast.LENGTH_LONG).show();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

	if (keyCode == KeyEvent.KEYCODE_BACK) {
	    Intent intent = null;
	    if (classname.equals("ReportAddActivity")) {
		intent = new Intent(OrderImageActivity.this, ReportNoRFIDActivity.class);
	    } else if (classname.equals("ReportNoRFIDActivity")) {
		intent = new Intent(OrderImageActivity.this, ReportNoRFIDActivity.class);
	    } else if (classname.equals("OrderOtherActivity")) {
		intent = new Intent(OrderImageActivity.this, OrderOtherActivity.class);
	    } else if (classname.equals("EquipementAddActivity")) {
		intent = new Intent(OrderImageActivity.this, EquipementAddActivity.class);
	    } else if (classname.equals("OrderOtherActivity")) {
		intent = new Intent(OrderImageActivity.this, OrderOtherActivity.class);
	    }
	    ;

	    Bundle bundle = new Bundle();
	    bundle.putStringArrayList("imgpath", imagepath);
	    intent.putExtras(bundle);
	    setResult(RESULT_OK, intent);
	}
	return super.onKeyDown(keyCode, event);
    }

    /**
     * 拍照
     */
    public void Photograph() {
	Intent intents = new Intent(OrderImageActivity.this, ScrawlActivity.class);
	intents.putExtra("classname", "OrderImageActivity");
	intents.putExtra("imgpath", "");
	startActivityForResult(intents, REQUEST_CODE_TAKE_IMAGE);
    }

}
